from flask import Flask, render_template, request, jsonify
import sqlite3
import os

db_path = 'db/shop.db'

def init_db():
    #订单表
    if not os.path.exists(db_path):
        conn = sqlite3.connect(db_path, timeout=10)
        # 创建商品表
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS products (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    price REAL NOT NULL,
                    image TEXT NOT NULL)''')
        conn.commit()
    
        # 创建购物车表
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS cart (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    product_id INTEGER NOT NULL,
                    quantity INTEGER NOT NULL,
                    price REAL NOT NULL,
                    FOREIGN KEY (product_id) REFERENCES products(id))''')
        conn.commit()

        # 创建支付表
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS payments (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    order_id TEXT NOT NULL,
                    amount REAL NOT NULL,
                    status TEXT NOT NULL,
                    payment_id TEXT NOT NULL)''')
        # 创建支付表
        c = conn.cursor()
        c.execute('''CREATE TABLE order_items (
            order_item_id INTEGER PRIMARY KEY AUTOINCREMENT,
            order_id TEXT NOT NULL,
            product_id INTEGER NOT NULL,
            quantity INTEGER NOT NULL,
            price REAL NOT NULL,
            total_price REAL NOT NULL,
            FOREIGN KEY (order_id) REFERENCES payments(order_id)
        );''')
        
        # 初始化一些商品数据
        c = conn.cursor()
        c.execute('''INSERT OR IGNORE INTO products (name, price, image) VALUES
                ('商品A', 100.0, 'imgs/img1.jpg'),
                ('商品B', 150.0, 'imgs/img2.jpg'),
                ('商品C', 200.0, 'imgs/img3.jpg')''')

        conn.commit()
        conn.close()
